package com.chen.handler;

import com.alibaba.fastjson.JSON;
import com.chen.api.RpcRequest;
import com.chen.api.RpcResponse;
import com.chen.filter.Filter;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RpcInvocationHandler implements InvocationHandler {

    public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");

    private final Class<?> serviceClass;
    private final String url;
    private final Filter[] filters;

    public RpcInvocationHandler(Class<?> serviceClass, String url, Filter[] filters) {
        this.serviceClass = serviceClass;
        this.url = url;
        this.filters = filters;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {

        RpcRequest request = new RpcRequest();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(params);

        if (null != filters){
            for (Filter filter : filters){
                if (!filter.filter(request)){
                    return null;
                }
            }
        }

        RpcResponse response = post(request,url);

        return JSON.parse(response.getResult().toString());
    }

    private RpcResponse post(RpcRequest rpcReq, String url) throws IOException {
        String reqJson = JSON.toJSONString(rpcReq);
        System.out.println("request json:"+ reqJson);

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSONTYPE,reqJson))
                .build();
        String respJson = client.newCall(request).execute().body().string();
        return JSON.parseObject(respJson,RpcResponse.class);
    }
}
